iT邦幫忙

2021 iThome 鐵人賽

DAY 20
0
AI & Data

想到甚麼打甚麼系列 第 20

找LeetCode上簡單的題目來撐過30天啦(DAY20)

  • 分享至 

  • xImage
  •  

這題寫凌晨2、3點,本來要用c的,最後用JAVA,然後睡覺前送出去Time Limit Exceeded,心都要碎了,好家在把print拿掉後就過了,可喜可賀?

題號3 標題:Longest Substring Without Repeating Characters 難度:Medium

Given a string s, find the length of the longest substring without repeating characters.

Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Example 4:
Input: s = ""
Output: 0

Constraints:
• 0 <= s.length <= 5 * 104
• s consists of English letters, digits, symbols and spaces.

我的程式碼

class Solution {
    public int lengthOfLongestSubstring(String s) {
        ArrayList<String> temp = new ArrayList<String>();
        
        int i=0,j=0,count=1,result=1;
        if(s.isEmpty()){
            return 0;
        }
        temp.add(Character.toString(s.charAt(0)));
        for(i=1;i<s.length();i++){
            String dtemps = Character.toString(s.charAt(i));
            if(temp.contains(dtemps)){
                //System.out.println(temp.indexOf(Character.toString(s.charAt(i))));
                int dtemp = temp.indexOf(dtemps);
                if(result<count){
                    result=count;
                }
                for(j=0;j<=dtemp;j++){
                    temp.remove(0);
                }
                if(temp.size()!=0){
                    count=temp.size();
                }else{
                    count = 0;
                }
                 
            }
            temp.add(dtemps);
            count++;
            // for(j=0;j<temp.size();j++){
            //     System.out.print(temp.get(j));
            // }
            // System.out.print(" count:"+count);
            System.out.println();
        }
        if(count>result){
            result = count;
        }
        return result;
    }
}

DAY20心得
終於走完1/3了,加油加油,來去倒垃圾


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY19)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY21)
系列文
想到甚麼打甚麼30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言